<template>
<div>
    <div v-if="goods">
      <goods :goods="goods"/>
    </div>
    <div v-if="emptyStatus">
      <not-found/>
    </div>
</div>

</template>

<script>
import * as ProductActions from '@/api/product'
import { mapState } from 'vuex'
import Goods from './components/goods'
import NotFound from './not-found'
import Utils from '@/utils'
export default {
  components: {
    'goods': Goods,
    'not-found': NotFound
  },
  data () {
    return {
      emptyStatus: false,
      goods: null,
      shareText: '',
      group_buy: null
    }
  },
  computed: {
    ...mapState(['me'])
  },
  onLoad (query) {
    this.goods = null
    this.group_buy = null
    wx.showNavigationBarLoading()
    wx.showShareMenu({ withShareTicket: true })
    if (this.$root.$mp.query.id) this.fetchProduct(this.$root.$mp.query.id)
    if (this.$root.$mp.query.code) {
      wx.setStorageSync('__inviteCode', this.$root.$mp.query.code)
      return
    }
    if (query.scene) {
      let params = Utils.parseQuery(decodeURIComponent(query.scene))
      if (params.id) this.fetchProduct(params.id)
      if (params.ic && params.ic.length === 6) wx.setStorageSync('__inviteCode', params.ic)
    }
  },
  onShow () {
    this.emptyStatus = false
  },
  onPullDownRefresh () {
    wx.showNavigationBarLoading()
    if (this.goods) this.fetchProduct(this.goods.id)
    wx.stopPullDownRefresh()
  },
  methods: {
    shareTitle () {
      if (!this.goods) return
      if (!this.me) return `美控小管家向您推荐${this.goods.title}`
      if (this.me) return `${this.me.nickname}向您推荐${this.goods.title}`
    },
    sharePath () {
      if (!this.goods) return
      if (!this.me) return '/pages/product/detail?id=' + this.goods.id
      if (this.me && this.me.invite_code) return '/pages/product/detail?code=' + this.me.invite_code + '&id=' + this.goods.id
    },
    fetchProduct (id) {
      ProductActions.show(id)
        .then(data => {
          this.goods = data
          wx.hideNavigationBarLoading()
        }).catch(() => {
          wx.hideNavigationBarLoading()
          this.emptyStatus = true
        })
    }
  },
  onShareAppMessage (res) {
    return {
      title: this.shareTitle(),
      imageUrl: this.goods.images[0],
      path: this.sharePath()
    }
  }
}
</script>
